package cn.whx.hrm.controller;

import cn.whx.hrm.doc.CourseDoc;
import cn.whx.hrm.mapper.HighlightResultMapper;
import cn.whx.hrm.query.CourseDocQuery;
import cn.whx.hrm.query.PageList;
import cn.whx.hrm.repository.CourseDocRepository;
import cn.whx.hrm.util.AjaxResult;
import cn.whx.hrm.vo.AggVo;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.PageRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/search")
public class CourseDocController {
    @Autowired
    private CourseDocRepository courseDocRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private HighlightResultMapper highlightResultMapper;
    @PostMapping("/courseDoc")
    @PreAuthorize("hasAuthority('courseDoc:add')")
    public AjaxResult add(@RequestBody CourseDoc courseDoc){
        //保存
        courseDocRepository.save(courseDoc);
        return AjaxResult.me();
    }
    //移除
    @PostMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable("id")Long id){
        courseDocRepository.deleteById(id);
        return AjaxResult.me();
    }
    @PostMapping("/queryCourses")
    public AjaxResult query(@RequestBody CourseDocQuery query){
        //创建一个query对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        BoolQueryBuilder bollQuery = QueryBuilders.boolQuery();
        //高级查询
        String keyword = query.getKeyword();
        if(StringUtils.isNotBlank(keyword)){
            bollQuery.must(QueryBuilders.multiMatchQuery(keyword,"name","courseTypeName","tenantName"));
        }
        String typeName = query.getCourseTypeName();
        if(StringUtils.isNotBlank(typeName)){
            bollQuery.must(QueryBuilders.termQuery("courseTypeName", typeName));
        }
        String tenantName = query.getTenantName();
        if(StringUtils.isNotBlank(tenantName)){
            bollQuery.must(QueryBuilders.termQuery("tenantName", tenantName));
        }
        //价格来过滤
        Float priceMax = query.getPriceMax();//最大价格
        if (priceMax !=null){
            bollQuery.filter(QueryBuilders.rangeQuery("price").lte(priceMax));//小于最大价格
        }
        Float priceMin = query.getPriceMin();//最小价格
        if (priceMin!=null){
            bollQuery.filter(QueryBuilders.rangeQuery("price").gte(priceMin));//大于最小价格
        }
        //排序
        String filed = query.getSortField();
        filed = StringUtils.isNotBlank(filed)?filed:"viewCount";//不是空的也不是filed就默认用人气
        FieldSortBuilder fieldSortBuilder = new FieldSortBuilder(filed);
        //排序类型
        String type = query.getSortType();
        SortOrder order = StringUtils.isNotBlank(type)&&type.equals(SortOrder.DESC.toString())?SortOrder.DESC:SortOrder.ASC;
        builder.withSort(fieldSortBuilder.order(order));
        //设置高亮的显示
        HighlightBuilder.Field hfield = new HighlightBuilder.Field("name").preTags("<font style='color:red'><b>").postTags("</b></font>");//显示红色
        //名字高亮
        builder.withHighlightFields(hfield);
        //分页
        builder.withPageable(PageRequest.of(query.getPage()-1, query.getRows()));
        //聚合查询
        builder.addAggregation(AggregationBuilders.terms("tenantNameAgg").field("tenantName").order(Terms.Order.count(false)).size(20));
        builder.addAggregation(AggregationBuilders.terms("courseTypeAgg").field("courseTypeName").order(Terms.Order.count(false)).size(20));
        AggregatedPage<CourseDoc> docs = elasticsearchTemplate.queryForPage(builder.build(), CourseDoc.class, highlightResultMapper);//elasticsearchTemplate才显示高亮
        //获取聚合查询的结果
        StringTerms tenantNameAgg = (StringTerms) docs.getAggregation("tenantNameAgg");
        //用list集合封装聚合查询
        ArrayList<AggVo> tenantAggs = new ArrayList<>();
        List<StringTerms.Bucket> tenantList = tenantNameAgg.getBuckets();
        //遍历
        tenantList.forEach(bucket ->{
            AggVo aggVo = new AggVo();
            aggVo.setCount(bucket.getDocCount());
            aggVo.setName(bucket.getKeyAsString());
            tenantAggs.add(aggVo);
        } );
        //获取聚合查询结果的
        StringTerms typeNameAgg = (StringTerms) docs.getAggregation("courseTypeAgg");
        //创建list集合封装机构名称聚合查询
        ArrayList<AggVo> typeAggs = new ArrayList<>();
        List<StringTerms.Bucket> typeList = typeNameAgg.getBuckets();
        typeList.forEach(bucket -> {
            AggVo aggVo = new AggVo();
            aggVo.setCount(bucket.getDocCount());
            aggVo.setName(bucket.getKeyAsString());
            typeAggs.add(aggVo);
        });
        //创立一个map封装聚合查询的结果
        HashMap<String, ArrayList<AggVo>> map = new HashMap<>();
        map.put("tenantAggs", tenantAggs);
        map.put("typeAggs", typeAggs);
        return  AjaxResult.me().setResultObj(new PageList<>(docs.getTotalElements(),docs.getContent(),map));

    }
}
